import {shop_fav,shop_unfav,shop_favlist} from '../../utils/api'

import { Toast } from 'vant'

export default {
    namespaced:true,//开启模块
    state:{
        collectlist:[]
    },
    mutations:{
        collect_shop(state,params){ //收藏店铺
            state.collectlist.push( params );
        },
        cancel_collect_shop(state,params){ //取消收藏店铺
        //查找店铺
        var index = state.collectlist.findIndex((item)=>{
            return item.mtWmPoiId == params.mtWmPoiId
        })
        if( index != -1){
            //取消收藏店铺
            state.collectlist.splice( index,1 );
        }
        },
        save_collectlist(state,params){ //保存收藏列表
            state.collectlist = params;
        }
    },
    actions:{
        //发请求 收藏店铺到数据库, 并同步到vuex
        request_collect_shop({ commit },params){
        //获取userinfo
        var userinfo = localStorage.getItem('userinfo') ? JSON.parse( localStorage.getItem('userinfo') ) : {};
        //发请求 收藏店铺到数据库
        shop_fav({ userid: userinfo.id , shopid: params.mtWmPoiId}).then((res)=>{
          if( res.data.code == 200 ){
            Toast.success(res.data.msg);
            commit('collect_shop',params);//调用同步方法 存店铺到store
          }
        })
        },
        //发请求 从数据库取消收藏店铺, 并同步到vuex
        request_cancel_collect_shop({ commit },params){
            //获取userinfo
            var userinfo = localStorage.getItem('userinfo') ? JSON.parse( localStorage.getItem('userinfo') ) : {};
            //发请求 从数据库取消收藏店铺
            shop_unfav({ userid: userinfo.id , shopid: params.mtWmPoiId}).then((res)=>{
            if( res.data.code == 200 ){
                Toast.success(res.data.msg);
                commit('cancel_collect_shop',params);//调用同步方法 从store删除店铺
            }
            })
        },
        //请求数据库中的收藏列表, 并同步到vuex
        request_collectlist({ commit },params){
            //获取userinfo
            var userinfo = localStorage.getItem('userinfo') ? JSON.parse( localStorage.getItem('userinfo') ) : {};
            shop_favlist({userid:userinfo.id}).then((res)=>{
            commit('save_collectlist',res.data.list);
            })
        },
    }
}